//
//  TTMenuLayout.m
//  TTScrollMenus-Demo
//
//  Created by 赵国腾 on 16/5/16.
//  Copyright © 2016年 赵国腾. All rights reserved.
//

#import "TTMenuLayout.h"

@interface TTMenuLayout ()

/** 布局数组 */
@property (nonatomic, strong) NSMutableArray *layoutAttributes;

@end

@implementation TTMenuLayout

- (instancetype)init {
    
    if (self = [super init]) {
        
        self.lineCount = 2; // 默认
        self.coluCount = 4; // 默认
        self.edgeInsets = UIEdgeInsetsZero;
    }
    
    return self;
}

- (NSMutableArray *)layoutAttributes {
    if (_layoutAttributes == nil) {
        _layoutAttributes = [NSMutableArray array];
    }
    return _layoutAttributes;
}

- (void)prepareLayout {
    
    [self.layoutAttributes removeAllObjects];
    
    NSInteger itemCount = [self.collectionView numberOfItemsInSection:0];
    
    for (NSInteger i = 0; i < itemCount; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        [self.layoutAttributes addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
    }
}

- (CGSize)collectionViewContentSize {
    
    CGFloat collectionViewW = CGRectGetWidth(self.collectionView.bounds);
    CGFloat collectionViewH = CGRectGetHeight(self.collectionView.bounds);
    
    UICollectionViewLayoutAttributes *lastLayout = self.layoutAttributes.lastObject;
    CGFloat lastMaxX = CGRectGetMaxX(lastLayout.frame);
    
    CGFloat sizeW = (NSInteger)ceilf(lastMaxX / collectionViewW) * collectionViewW;
    return CGSizeMake(sizeW, collectionViewH);
}

- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    return self.layoutAttributes;
}

- (nullable UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewLayoutAttributes *layout = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    CGFloat collectionViewW = CGRectGetWidth(self.collectionView.bounds);
    CGFloat collectionViewH = CGRectGetHeight(self.collectionView.bounds);

    // cell的高度 & 宽度
    CGFloat itemW = collectionViewW / self.coluCount;
    CGFloat itemH = (collectionViewH - self.edgeInsets.top - self.edgeInsets.bottom) / self.lineCount;

    if (indexPath.item < self.lineCount) {
        
        layout.frame = CGRectMake(0, self.edgeInsets.top + itemH * indexPath.item, itemW, itemH);
        return layout;
    }

    UICollectionViewLayoutAttributes *beBeforeLayout = self.layoutAttributes[indexPath.item - self.lineCount];
    CGRect beBeforeFrame = beBeforeLayout.frame;
    layout.frame = CGRectMake(CGRectGetMaxX(beBeforeFrame), CGRectGetMinY(beBeforeFrame), itemW, itemH);
    
    return layout;
}

@end
